<template>
<div class="page">
  <div class="search">
    <a-form-model :form="form" :label-col="labelCol" :wrapper-col="wrapperCol" @submit.pre.prevent="search">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="商户/商圈名称" prop="mchntName">
            <a-input v-model="form.mchntName" placeholder="请输入商户/商圈名称"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="商户号/商圈号" prop="mchntNo">
            <a-input v-model="form.mchntNo" placeholder="请输入商户/商圈名称"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="营销方式" prop="cashbackMethod">
            <a-select v-model="form.cashbackMethod" placeholder="请选择营销方式">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option value="0">按交易金额比例返现</a-select-option>
              <a-select-option value="1">按交易金额固定返现</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="活动状态" prop="mcStatus">
            <a-select v-model="form.mcStatus" placeholder="请选择活动状态">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option value="0">草稿</a-select-option>
              <a-select-option value="1">未发布</a-select-option>
              <a-select-option value="2">进行中</a-select-option>
              <a-select-option value="3">已暂停</a-select-option>
              <a-select-option value="9">已结束</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="创建时间" prop="mchntName">
            <a-range-picker v-model="form.rangeDate"></a-range-picker>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: center;">
          <a-space>
            <a-button type="primary" html-type="submit">查询</a-button>
            <a-button @click="reset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
  <div class="operation">
    <a-space>
      <a-button type="primary" icon="plus" @click="add">新增</a-button>
    </a-space>
  </div>
  <a-table :data-source="dataSource" :columns="columns" :pagination="pagination" :scroll="{x: true}" row-key="mcNo" class="scrollable" @change="pageChange">
    <template v-slot:operation="text, record">
      <div style="white-space: nowrap">
        <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改" v-has-permission="['cashierManager:edit']"></a-icon>
        <a-icon type="eye" theme="twoTone" twoToneColor="#4a9ff5" @click="view(record)" title="详情" v-has-permission="['cashierManager:view']"></a-icon>
        <a-icon type="container" theme="twoTone" twoToneColor="#4a9ff5" @click="paymentDetail(record)" title="收银员打款明细" v-has-permission="['cashierManager:view']"></a-icon>
        <a-icon type="delete" theme="twoTone" twoToneColor="red" @click="del(record)" title="删除" v-has-permission="['cashierManager:delete']"></a-icon>
      </div>
   </template>
  </a-table>
  <cashier-manager-operation ref="cashierManagerOperation" @refresh="fetch"></cashier-manager-operation>
  <payment-detail ref="paymentDetail"></payment-detail>
</div>
</template>

<script>
import CashierManagerOperation from './CashierManagerOperation'
import PaymentDetail from './PaymentDetail'
import moment from 'moment'

/**
 * 银行对收银员营销活动发布
 * 原系统代码支持对活动的 暂停、终止、启用操作。但是没有在权限管理里设置权限。本次迁移不包含此操作。 2022-06-22
 */
export default {
  name: "CashierManager",
  components: {CashierManagerOperation, PaymentDetail},
  data () {
    return {
      form: {
        mchntName: "",
        mchntNo: "",
        cashbackMethod: "",
        mcStatus: "",
        rangeDate: null,
      },
      labelCol: {span:8},
      wrapperCol: {span: 16},
      dataSource: [],
      columns: [
        {title: '优惠活动名称', dataIndex: 'mcName'},
        {title: '营销活动编号', dataIndex: 'mcNo'},
        {
          title: '活动起始时间',
          dataIndex: 'mcStartDate',
          customRender(text) {
            return moment(text).format('YYYY-MM-DD')
          }
        },
        {
          title: '活动终止时间',
          dataIndex: 'mcEndDate',
          customRender(text) {
            return moment(text).format('YYYY-MM-DD')
          }},
        {
          title: '活动状态',
          dataIndex: 'mcStatus',
          customRender (text) {
            return ({
              "0": "草稿",
              "1": "未发布",
              "2": "进行中",
              "3": "已暂停",
              "4": "自然结束",
              "5": "强制结束",
              "6": "测试中",
              "9": "已结束",
            }[text]) || ''
          }
        },
        {
          title: '活动审核状态',
          dataIndex: 'auditStatus',
          customRender (text) {
            return ({
              "00": "待提交审批",
              "01": "新增-审批流程中",
              "02": "新增-审批通过",
              "03": "新增-审批拒绝",
              "11": "注销-审批流程中",
              "12": "注销-审批通过",
              "13": "注销-审批拒绝",
              "21": "停用-审批流程中",
              "22": "停用-审批通过",
              "23": "停用-审批拒绝",
              "31": "启用-审批流程中",
              "32": "启用-审批通过",
              "33": "启用-审批拒绝",
              "41": "修改-审批流程中",
              "42": "修改-审批通过",
              "43": "修改-审批拒绝",
              "51": "发布-审批流程中",
              "52": "发布-审批通过",
              "53": "发布-审批拒绝",
            }[text]) || ''
          }
        },
        {
          title: '营销方式',
          dataIndex: 'cashbackMethod',
          customRender (text) {
            return ({
              "0": "按交易金额比例返现",
              "1": "按交易金额固定返现",
            }[text]) || ''
          }
        },
        {title: '营销预算(元)', dataIndex: 'budget'},
        {title: '已消耗预算(元)', dataIndex: 'budgetUsed'},
        {title: '创建人', dataIndex: 'oprId'},
        {
          title: '创建时间',
          dataIndex: 'createTime',
          customRender (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss')
          }
        },
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: {customRender: 'operation'}
        }
      ],
      pagination: {
        pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
    }
  },
  methods: {
    pageChange (e) {
      this.pagination.current = e.current;
      this.pagination.pageSize = e.pageSize;
      this.fetch();
    },
    search () {
      this.pagination = Object.assign({} ,{
        current: 1,
        pageSize: 10
      })
      this.fetch();
    },
    reset () {
      this.form = {
        mchntName: "",
        mchntNo: "",
        cashbackMethod: "",
        mcStatus: "",
        rangeDate: null,
      };
      this.search();
    },
    async fetch () {
      let params = {
        mchntName: this.form.mchntName || null,
        mchntNo: this.form.mchntNo || null,
        cashbackMethod: this.form.cashbackMethod || null,
        mcStatus: this.form.mcStatus || null,
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      if (this.form.rangeDate && this.form.rangeDate.length === 2) {
        params.startTime = this.form.rangeDate[0].format('YYYY-MM-DD') + " 00:00";
        params.endTime = this.form.rangeDate[1].format('YYYY-MM-DD') + " 23:59";
      }
      const hideLoading = this.$message.loading("加载中...");
      try {
        const res = await this.$get('/admin/market/cashierManager/getMcInfo', params)
        this.dataSource = res.data.records || [];
        this.$set(this.pagination, "total", +res.data.total);
      } catch (e) {
        this.$message.error('网络错误，请稍后再试！')
        console.error(e)
      }
      hideLoading()
    },
    resolveBeanInfo(data) {
      const detailData = JSON.parse(data.datailData)
      const mcInfoObj = detailData.mcInfoObj;
      const orgInfoList = detailData.orgInfoList;
      const mchntInfoList = detailData.mchntInfoList;
      const productInfoList = detailData.productInfoList;
      const ruleInfoList = detailData.ruleInfoList;
      return {
        mcNo: data.mcNo, // 营销活动编号
        mcName: mcInfoObj.mcName, // 营销活动名称
        orgInfo: orgInfoList.map(i => i.orgId), // 参与机构
        mcDateRange: [moment(mcInfoObj.mcStartDate), moment(mcInfoObj.mcEndDate)], // 活动起始时间
        discountTransferMode: mcInfoObj.discountTransferMode, // 活动优惠方式
        budget: +mcInfoObj.budget, // 返现金额  数字格式 隐式转换
        merchantInfo: mchntInfoList.filter(i => i.mchntType === '0'), // 商户信息
        merchantCircleInfo: mchntInfoList.filter(i => i.mchntType === '1'), // 商圈信息
        upLineProduce: productInfoList.map(i => i.bizProdCode), // 纳入营销的交易
        criteriaLimit: +mcInfoObj.criteriaLimit, // 有效交易定义
        statPeriod: mcInfoObj.statPeriod, // 统计周期
        criteriaAmount: +mcInfoObj.criteriaAmount, // 周期内收银员交易金额达标
        criteriaFlag: mcInfoObj.criteriaFlag, // 周期内收银员交易金额达标条件计算方式
        criteriaQuantity: +mcInfoObj.criteriaQuantity, // 周期内收银员交易笔数达标
        cashbackMethod: mcInfoObj.cashbackMethod, // 营销方式交易类型
        ruleInfo: ruleInfoList, // 营销方式阶梯规则
        quantityLimitPerson: mcInfoObj.quantityLimitPerson, // 单个收银员统计交易笔数上限
        amountLimitPerson: mcInfoObj.amountLimitPerson, // 单个收银员统计交易金额上限
        cashbackLimitPerson: mcInfoObj.cashbackLimitPerson, // 单个收银员返现金额上限
        quantityLimitMc: mcInfoObj.quantityLimitMc, // 纳入返现总交易笔数上限
        amountLimitMc: mcInfoObj.amountLimitMc, // 纳入返现总交易金额上限
        cashbackLimitMc: mcInfoObj.cashbackLimitMc, // 返现总金额上限
        publishRefuseReason: mcInfoObj.publishRefuseReason, // 发布意见
        auditRefuseReason: mcInfoObj.auditRefuseReason, // 审核意见
        payAcctNo: mcInfoObj.payAcctNo, // 支付账号
      }
    },
    async edit (record) {
      if (record.attendFlag === "1") {
        this.$message.error("上级行创建的活动没有权限操作");
        return;
      }
      if (record.auditStatus !== "00" && record.auditStatus !== "03" && record.auditStatus !== "43" && record.auditStatus !== "53") {
        this.$message.error('只能修改审批状态为待提交审批的或者审批拒绝的营销活动数据！');
        return;
      }

      if (record.auditStatus === "04") {
        this.$message.error('该营销活动正在处理中，不能修改，请先查询状态是否已变更');
        await this.fetch()
        return;
      }
      const hide = this.$message.loading('加载中...', 0);
      try {
        const res = await this.$get('/admin/market/cashierManager/toEdit?mcNo=' + record.mcNo)
        if(res.data.datailData) {
          this.$refs.cashierManagerOperation.show(this.resolveBeanInfo(res.data), 'edit')
        }
      } catch (e) {
        console.error(e)
      }
      hide()
    },
    async view (record) {
      const hide = this.$message.loading("加载中...", 0);
      try {
        const res = await this.$get('/admin/market/cashierManager/toDetails?mcNo=' + record.mcNo)
        if(res.data.datailData) {
          this.$refs.cashierManagerOperation.show(this.resolveBeanInfo(res.data), 'view')
        }
      } catch (e) {
        console.error(e)
      }
      hide()
    },
    async del (record) {
      try {
        if (record.attendFlag === "1") {
          this.$message.error("上级行创建的活动没有权限操作");
          return;
        }
        if (record.mcStatus !== "0") {
          this.$message.error('只可删除草稿状态的营销活动！');
          return;
        }
        if (record.auditStatus === "04") {
          this.$message.error('该营销活动正在审批中，不能被删除');
          await this.fetch()
          return;
        }
        this.$confirm({
          title: '提示',
          content: '确认删除该营销活动吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: async () => {
            const res = await this.$post('/admin/market/cashierManager/deleteMcData', {
              mcNo: record.mcNo
            })
            if (res.data.code === '100000') {
              this.$message.success('删除成功')
              await this.fetch()
            } else {
              this.$message.error(res.data.message)
            }
          }
        })
      } catch (e) {
        console.error(e)
      }
    },
    add () {
      this.$refs.cashierManagerOperation.show({}, 'add')
    },
    paymentDetail (record) {
      this.$refs.paymentDetail.show(record.mcNo)
    }
  },
  mounted () {
    this.fetch();
  }
}
</script>

<style scoped>
.operation {
  margin-bottom: 10px;
}
.page {
  width: 100%;
}
/deep/ .scrollable .ant-table td {
  white-space: nowrap;
}
</style>
